package com.yunban.project.api.text_check.controller;

import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.domain.TempCorrectRecord;
import com.yunban.project.api.text_check.domain.UserCorrectionCharLimit;
import com.yunban.project.api.text_check.dto.CorrectTaskResp;
import com.yunban.project.api.text_check.dto.CorrectionReq;
import com.yunban.project.api.text_check.dto.ReadLinkTextReq;
import com.yunban.project.api.text_check.dto.TestCorrectReq;
import com.yunban.project.api.text_check.dto.deepseek.ChatReq;
import com.yunban.project.api.text_check.dto.deepseek.enums.DeepSeekModel;
import com.yunban.project.api.text_check.enums.CorrectionModel;
import com.yunban.project.api.text_check.service.*;
import com.yunban.project.api.text_check.service.impl.CorrectionFactory;
import com.yunban.project.api.text_check.service.impl.HunYuanApplicationCorrectionService;
import com.yunban.project.api.text_check.service.impl.HuoShanCorrectionService;
import com.yunban.project.api.text_check.vo.CreateCorrectTaskResp;
import com.yunban.project.api.text_check.vo.UserCorrectionCharLimitResp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * @author: lijiajun
 * @date: 2024-11-22
 * @version: 1.0
 */
@RestController
@Tag(name = "文本纠错管理")
@RequestMapping("/correction-api")
public class CorrectionController {

    @Resource
    private CorrectionFactory correctionFactory;

    @Resource
    private CorrectionService correctionService;

    @Resource
    @Qualifier("baiduAiCorrectionService")
    private AiCorrectionService aiCorrectionService;

    @Resource
    private CorrectionConfigService correctionConfigService;

    @Resource
    private UserCorrectionCharLimitService userCorrectionCharLimitService;

    @NoNeedLogin
    @PostMapping("/read/word")
    @Operation(summary = "读取word中的文本信息")
    String readWordText(@RequestParam("file") MultipartFile file) {
        return this.correctionService.readWord(file);
    }

    @NoNeedLogin
    @PostMapping("/read/link")
    String readLinkText(@RequestBody @Validated ReadLinkTextReq req) {
        return this.correctionService.readLinkText(req.getLink());
    }


//    public static void main(String[] args) {
//        List<String> punctuateList = Arrays.asList(";", "!", "?", "。", "！", "？", "；", "\n", "\\n");
//        String text = "软件工程师\n我是一位软键工程师";
//        String regex = punctuateList.stream().map(Pattern::quote).collect(Collectors.joining("|"));
//        Pattern pattern = Pattern.compile(regex);
//        Matcher matcher = pattern.matcher(text);
//        int lastEnd = 0;
//        // 从1开始计数
//        int order = 1;
//        List<Map<String, Object>> result = new ArrayList<>();
//        while (matcher.find()) {
//            String str = text.substring(lastEnd, matcher.end());
//            if (lastEnd != matcher.start() || str.length() == 1) {
//                // 添加从上一个分隔符结束位置到当前分隔符开始位置的文本段
//                String segmentText = text.substring(lastEnd, matcher.end());
//
//                HashMap<String, Object> map = new HashMap<>();
//                map.put("text", segmentText);
//                map.put("start", lastEnd);
//                map.put("end", matcher.end() - 1);
//                result.add(map);
//            }
//            lastEnd = matcher.end();
//        }
//
//        // 添加最后一个段落到结果列表（如果有的话）
//        if (lastEnd < text.length()) {
//            HashMap<String, Object> map1 = new HashMap<>();
//            map1.put("text", text.substring(lastEnd));
//            map1.put("start", lastEnd);
//            map1.put("end", text.length() - 1);
//            result.add(map1);
////            result.add(new CorrectUtils.TextSegment(order, text.substring(lastEnd), lastEnd, text.length() - 1));
//        }
//        List<Map<String, Object>> r = result.stream().filter(segment -> !ObjectUtils.isEmpty(segment.get("text"))).collect(Collectors.toList());
//
//        System.out.println(r);
//    }

    //    @NoNeedLogin
    @PostMapping("/create/task")
    @Operation(summary = "创建纠错任务")
    CreateCorrectTaskResp createCorrectTask(@RequestBody @Validated CorrectionReq req) {
        return this.correctionFactory.createCorrectTask(req.getText(), req.getSentencesPerSegment());
    }

    @NoNeedLogin
    @GetMapping("/task/{taskId}")
    @Operation(summary = "获取纠错结果")
    CorrectTaskResp getCorrectTask(@PathVariable String taskId) {
        return this.correctionFactory.getCorrectTask(taskId);
    }

    @GetMapping("/user/char/limit/info")
    @Operation(summary = "获取用户可用纠错字符数")
    UserCorrectionCharLimitResp getUserCharLimit() {
        UserCorrectionCharLimit charLimit = this.userCorrectionCharLimitService.findByUserId(SmartRequestUtil.getUserId());
        return new UserCorrectionCharLimitResp(charLimit.getTotalCharLimit(), charLimit.getUsedCharLimit());
    }

    @Resource
    private DeepSeekService deepSeekService;

    @Resource
    private TempCorrectRecordService tempCorrectRecordService;

    @NoNeedLogin
    @PostMapping("/test")
    ResponseDTO<String> testCorrect(@RequestBody TestCorrectReq req) {
        throw new BusinessException("暂不支持此接口");
//        String result = this.tempCorrectRecordService.saveRecord(req);
//        String result = null;
//        switch (req.getModel()) {
//            case "DeepSeek":
//                ChatReq chatReq = new ChatReq();
//                chatReq.setModel(DeepSeekModel.DEEPSEEK_V3.getModel());
//                chatReq.setMessage(req.getText());
//
//                CorrectionConfig config0 = this.correctionConfigService.findByCode(CorrectionModel.HUO_SHAN);
//
//                if (StringUtils.hasText(req.getPrompt())) {
//                    chatReq.setMessage(req.getPrompt() + req.getText());
//                } else {
//                    chatReq.setMessage(config0.getPromptPrefix() + req.getText());
//                }
//                result = this.deepSeekService.chat(chatReq);
//                break;
////                return ResponseDTO.ok(this.tempCorrectRecordService.saveRecord(req));
//            case "HuoShan":
//                HuoShanCorrectionService service = new HuoShanCorrectionService();
//                CorrectionConfig config1 = this.correctionConfigService.findByCode(CorrectionModel.HUO_SHAN);
//                if (StringUtils.hasText(req.getPrompt())) {
//                    config1.setPromptPrefix(req.getPrompt());
//                }
//                result = service.correctionV2(req.getText(), config1);
//                break;
//            case "Tencent":
//                HunYuanApplicationCorrectionService tencentService = new HunYuanApplicationCorrectionService();
//                CorrectionConfig config2 = this.correctionConfigService.findByCode(CorrectionModel.HUO_SHAN);
//                if (StringUtils.hasText(req.getPrompt())) {
//                    config2.setPromptPrefix(req.getPrompt());
//                }
//                result = tencentService.correctionV2(req.getText(), config2);
//                break;
//            default:
//                throw new BusinessException("参数错误");
//        }
//        return ResponseDTO.ok(result);
    }

    @NoNeedLogin
    @GetMapping("/test/{taskId}")
    TempCorrectRecord findByTaskId(@PathVariable String taskId) {
        return this.tempCorrectRecordService.findByTaskId(taskId);
    }
}
